<?php

namespace app\admin\controller\onlineclassroom;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 空中课堂管理
 *
 * @icon fa fa-video-camera
 * @controllerRoute onlineclassroom
 */
class Onlineclassroom extends Backend
{
    /**
     * OnlineClassroom模型对象
     * @var \app\admin\model\OnlineClassroom
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\OnlineClassroom;
        $this->view->assign("courseTypeList", $this->model->getCourseTypeList());
        $this->view->assign("isCompletedList", $this->model->getIsCompletedList());
        $this->view->assign("deviceTypeList", $this->model->getDeviceTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 添加城市和学校过滤逻辑
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 如果用户组为2（社区管理用户），只能看到自己城市的数据
            if ($_SESSION['think']['admin']['group_id'] == 2) {
                $city_id = $_SESSION['think']['admin']['city_id'];
            }
            
            // 构建查询对象
            $query = $this->model->with(['user'])->where($where);
            
            // 添加城市和学校过滤条件
            if ($city_id) {
                // 修改:明确指定表名前缀，避免字段歧义
                $query->where('online_classroom.city_id', $city_id);
            }
            if ($school_id) {
                // 修改:明确指定表名前缀，避免字段歧义
                $query->where('online_classroom.school_id', $school_id);
            }
            
            $list = $query->order($sort, $order)->paginate($limit);
            $total=$list->total();
            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username', 'nickname']);
            }
            $list = collection($list->items())->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                // 处理空的日期时间字段
                if (isset($params['start_time']) && $params['start_time'] === '') {
                    $params['start_time'] = null;
                }
                if (isset($params['end_time']) && $params['end_time'] === '') {
                    $params['end_time'] = null;
                }
                
                // 完全移除时间戳字段，让模型自动处理
                unset($params['create_time']);
                unset($params['update_time']);
                
                // 如果存在其他可能的时间戳字段，也要移除
                if (isset($params['createtime'])) {
                    unset($params['createtime']);
                }
                if (isset($params['updatetime'])) {
                    unset($params['updatetime']);
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\", "/", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    // 使用原始MySQL方法入库
                    $result = Db::name('online_classroom')->insert($params);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin", $_SESSION['think']['admin']['city_id']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                try {
                    Db::startTrans();
                    
                    // 处理空的日期时间字段
                    if (isset($params['start_time']) && $params['start_time'] === '') {
                        $params['start_time'] = null;
                    }
                    if (isset($params['end_time']) && $params['end_time'] === '') {
                        $params['end_time'] = null;
                    }
                    
                    // 移除时间戳字段，让模型完全自动处理
                    unset($params['create_time']);
                    unset($params['update_time']);
                    unset($params['createtime']);
                    unset($params['updatetime']);
                    
                    // 使用save方法，不使用allowField(true)
                    $result = $this->model->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            // 使用 force(true) 强制删除，避免软删除时出现时间格式错误
            $list = $this->model->where($pk, 'in', $ids)->delete();
            if ($list) {
                $this->success(__('Deleted successfully'));
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}